﻿#include "stdafx.h"
#include "GameService.h"
#include "../Message/Msg_Game.pb.h"
#include "../Message/Msg_RetCode.pb.h"
#include "../Message/Msg_ID.pb.h"
#include "WatcherClient.h"
#include "LogicSvrMgr.h"

CGameService::CGameService(void)
{
}

CGameService::~CGameService(void)
{

}

CGameService* CGameService::GetInstance()
{
	static CGameService _GameService;

	return &_GameService;
}

BOOL CGameService::Init()
{
	CommonFunc::SetCurrentWorkDir("");

	if(!CLog::GetInstance()->Start("CenterServer", "log"))
	{
		return FALSE;
	}
	CLog::GetInstance()->LogInfo("---------服务器开始启动--------");
	if(!CConfigFile::GetInstance()->Load("servercfg.ini"))
	{
		CLog::GetInstance()->LogError("配制文件加载失败!");
		return FALSE;
	}

	if (CommonFunc::IsAlreadyRun("CenterServer"))
	{
		CLog::GetInstance()->LogError("CenterServer己经在运行!");
		return FALSE;
	}

	CLog::GetInstance()->SetLogLevel(CConfigFile::GetInstance()->GetIntValue("center_log_level"));


	UINT16 nPort = CConfigFile::GetInstance()->GetIntValue("center_svr_port");
	if (nPort <= 0)
	{
		CLog::GetInstance()->LogError("配制文件center_svr_port配制错误!");
		return FALSE;
	}
	INT32  nMaxConn = CConfigFile::GetInstance()->GetIntValue("center_svr_max_con");
	if(!ServiceBase::GetInstance()->StartNetwork(nPort, nMaxConn, this))
	{
		CLog::GetInstance()->LogError("启动服务失败!");
		return FALSE;
	}

	ERROR_RETURN_FALSE(m_CenterMsgHandler.Init(0));
	CLog::GetInstance()->LogError("---------服务器启动成功!--------");
	return TRUE;
}


BOOL CGameService::OnNewConnect(INT32 nConnID)
{
	CWatcherClient::GetInstance()->OnNewConnect(nConnID);

	return TRUE;
}

BOOL CGameService::OnCloseConnect(INT32 nConnID)
{
	CWatcherClient::GetInstance()->OnCloseConnect(nConnID);

	LogicSvrMgr::GetInstance()->OnCloseConnect(nConnID);

	return TRUE;
}

BOOL CGameService::OnSecondTimer()
{
	CWatcherClient::GetInstance()->OnSecondTimer();

	return TRUE;
}

BOOL CGameService::DispatchPacket(NetPacket* pNetPacket)
{
	if (CWatcherClient::GetInstance()->DispatchPacket(pNetPacket))
	{
		return TRUE;
	}

	if (m_CenterMsgHandler.DispatchPacket(pNetPacket))
	{
		return TRUE;
	}

	return FALSE;
}

BOOL CGameService::Uninit()
{
	CLog::GetInstance()->LogError("==========服务器开始关闭=======================");

	ServiceBase::GetInstance()->StopNetwork();

	m_CenterMsgHandler.Uninit();

	google::protobuf::ShutdownProtobufLibrary();

	CLog::GetInstance()->LogError("==========服务器关闭完成=======================");

	return TRUE;
}

BOOL CGameService::Run()
{
	while (CWatcherClient::GetInstance()->IsRun())
	{
		ServiceBase::GetInstance()->Update();

		CommonFunc::Sleep(1);
	}

	return TRUE;
}


